# coding: utf-8
import os, sys
home = os.path.dirname(os.path.abspath(sys.argv[0]))
import time
from PyQt4 import QtCore, QtGui
import storage, dialog, task

class MyStandardItemModel(QtGui.QStandardItemModel):
    def flags(self, index):
        #return QtCore.Qt.ItemFlags(QtCore.Qt.ItemIsSelectable)
        return QtGui.QStandardItemModel.flags(self, index) & ~QtCore.Qt.ItemIsEditable

class MyTreeView (QtGui.QTreeView):
    def __init__(self, parent):
        super(MyTreeView, self).__init__()
        self.parent = parent

    def mouseDoubleClickEvent(self, event):
        indexes = self.selectedIndexes()
        rows = set()
        for x in indexes:
            rows.add(x.row())
        
        idx = list(rows)[0]
        idstr = self.parent.model.data(self.parent.model.index(idx, 0)).toString()
        id = int(idstr)
        row = self.parent.store.find(id)
        
        self.parent.dialog_add_task(row)
 

class MainWindow (QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        
        self.create_menu()
        self.create_toolbar()
        self.create_statusbar()
        self.create_systray()
        self.create_view()

        self.init()

        self.setWindowTitle("YouTask")
        self.resize(800, 500)
        
        self.task_thread = task.TaskThread(self.store)
        self.connect(self.task_thread, self.task_thread.task_timeout, self.taskArrived)
        self.task_thread.start()

    def create_menu(self):
        self.exitAct = QtGui.QAction(u"退出", self, shortcut="Ctrl+Q", 
                statusTip=u"退出程序", triggered=self.close)

        self.fileMenu = self.menuBar().addMenu(u'文件')
        self.fileMenu.addAction(self.exitAct)

        self.addTaskAct = QtGui.QAction(QtGui.QIcon('images/add.png'),
                u"添加任务", self, shortcut="Ctrl+A", 
                statusTip=u"添加任务", triggered=self.OnAddTask)

        self.delTaskAct = QtGui.QAction(QtGui.QIcon('images/del.png'),
                u"删除任务", self, shortcut="Ctrl+D", 
                statusTip=u"删除任务", triggered=self.OnDelTask)
 
        self.taskMenu = self.menuBar().addMenu(u"任务")
        self.taskMenu.addAction(self.addTaskAct)
        self.taskMenu.addAction(self.delTaskAct)

    def create_toolbar(self):
        self.fileToolBar = self.addToolBar(u"任务")
        self.fileToolBar.setIconSize(QtCore.QSize(48, 48))
        self.fileToolBar.addAction(self.addTaskAct) 
        self.fileToolBar.addAction(self.delTaskAct) 

    def create_statusbar(self):
        self.statusBar().showMessage("OK")

    def create_systray(self):
        self.showAct = QtGui.QAction(u"显示窗口", self, triggered=self.showNormal)
        self.hideAct = QtGui.QAction(u"隐藏窗口", self, triggered=self.hide)
        #self.quitAct = QtGui.QAction(u"退出", self, triggered=QtGui.qApp.quit)
        self.quitAct = QtGui.QAction(u"退出", self, triggered=sys.exit)
        self.trayMenu = QtGui.QMenu(self)
        self.trayMenu.addAction(self.showAct)
        self.trayMenu.addAction(self.hideAct)
        self.trayMenu.addAction(self.quitAct)

        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayMenu)

        icon = QtGui.QIcon("images/youtask.png")
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)

        self.trayIcon.show()

    def create_view(self):
        #self.taskView = QtGui.QTreeView()
        self.taskView = MyTreeView(self)
        self.taskView.setRootIsDecorated(False)
        self.taskView.setAlternatingRowColors(True)
        self.setCentralWidget(self.taskView)

        #self.model = QtGui.QStandardItemModel(0, 6, self)
        self.model = MyStandardItemModel(0, 6, self)
        self.model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
        self.model.setHeaderData(1, QtCore.Qt.Horizontal, u"标题")
        self.model.setHeaderData(2, QtCore.Qt.Horizontal, u"日期")
        self.model.setHeaderData(3, QtCore.Qt.Horizontal, u"时间")
        self.model.setHeaderData(4, QtCore.Qt.Horizontal, u"是否循环")
        self.model.setHeaderData(5, QtCore.Qt.Horizontal, u"提醒信息")
        
        self.taskView.setModel(self.model)
        self.taskView.setColumnWidth(0, 40)
        self.taskView.setColumnWidth(1, 200)

    def init(self):
        dbpath = os.path.join(home, "task.dat")
        self.store = storage.Storage(dbpath)

        self.reloadData()

    def OnAddTask(self):
        self.dialog_add_task()

    def dialog_add_task(self, data=None):
        dlg = dialog.DialogAdd(self)
        if data:
            dlg.setdata(data)
        dlg.setModal(True)
        while dlg.exec_():
            title = dlg.title.text()
            if not title:
                QtGui.QMessageBox.information(self, u'添加错误', u'标题不能为空')
                continue
            dt    = dlg.date.date()
            tm    = dlg.time.time()
            islp  = dlg.notify.isChecked()
            text  = dlg.message.toPlainText()

            x = {'title':unicode(title.toUtf8(), 'utf-8'), 
                 'date':[dt.year(), dt.month(), dt.day()], 
                 'time':[tm.hour(), tm.minute()],
                 'loop':islp, 
                 'msg':unicode(text.toUtf8(), 'utf-8')}

            if dlg.dataid == 0:
                self.store.addrow(x)
            else:
                self.store.updaterow(dlg.dataid, x)
            self.store.dump()

            self.reloadData()
            break
        dlg.destroy() 


    def OnDelTask(self):
        indexes = self.taskView.selectedIndexes()
        rows = set()
        for x in indexes:
            rows.add(x.row())
        
        for idx in rows:
            idstr = self.model.data(self.model.index(idx, 0)).toString()
            self.store.remove(int(idstr))
            self.model.removeRows(idx, 1)
        
        self.store.dump()

    def reloadData(self):
        self.model.removeRows(0, self.model.rowCount())
        data = self.store.data
        for row in data:
            self.model.insertRow(0)
            self.model.setData(self.model.index(0, 0), str(row['id']))
            self.model.setData(self.model.index(0, 1), row['title'])
            self.model.setData(self.model.index(0, 2), '%d-%02d-%02d' % tuple(row['date']))
            self.model.setData(self.model.index(0, 3), '%02d:%02d' % tuple(row['time']))
            if row['loop']:
                self.model.setData(self.model.index(0, 4), u'是')
            else:
                self.model.setData(self.model.index(0, 4), u'否')
            self.model.setData(self.model.index(0, 5), row['msg'])
    

    def taskArrived(self, row):
        QtGui.QMessageBox.information(self, row['title'], row['msg'])
        #self.store.lasttime_refresh(row['id'])

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    QtGui.QApplication.setQuitOnLastWindowClosed(False)
    mainwin = MainWindow()
    mainwin.show()
    sys.exit(app.exec_())

